package com.chis.utils;

import com.frameworkset.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author cl
 * @version 2020年05月07日
 * @Description 读取配置文件
 * @Company zwx
 */
@Slf4j
public class ReadPropertiesUtil {

    /**
     * 读取外部Properties配置
     *
     * @param props 默认配置名称
     * @return 结果
     */
    public static Properties readProperties(String props) {
        Properties prop = new Properties();
        try {
            InputStream inputStream;
            // 读取文件
            String systemProp = System.getProperty("props");
            Boolean isOut = StringUtil.hasText(systemProp);
            props = isOut ? systemProp : props;
            if (isOut) {
                inputStream = new FileInputStream(props);
            } else {
                inputStream = ReadPropertiesUtil.class.getClassLoader().getResourceAsStream(props);
            }
            prop.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return prop;
    }


    /**
     * 读取配置路径文件
     *
     * @param redProps 需要读取的默认参数名
     * @param pathName 配置参数
     * @param props 核心配置文件
     * @return 读取结果
     */
    public static Properties readPathProperties(String redProps, String pathName,String props) {
        Properties properties = ReadPropertiesUtil.readProperties(props);
        Properties prop = new Properties();
        try {
            InputStream inputStream;
            Boolean isOut = false;
            if (properties.get(pathName) != null && new File(properties.get(pathName).toString()).exists()) {
                redProps = properties.get(pathName).toString();
                isOut = true;
            }

            // 读取文件
            if (isOut) {
                inputStream = new FileInputStream(redProps);
            } else {
                inputStream = ReadPropertiesUtil.class.getClassLoader().getResourceAsStream(redProps);
            }
            prop.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return prop;
    }
}
